<!--  -->
<template>
  <div class="">
    <heads></heads>
    <main>
      <template>
        <el-table :data="tableData" stripe style="width: 100%">
          <el-table-column prop="addUserTime" label="日期" width="180"> </el-table-column>
          <el-table-column prop="username" label="姓名" width="180"> </el-table-column>
          <el-table-column prop="address" label="地址"> </el-table-column>

          <el-table-column prop="userImg" label="头像">
            <template slot-scope="scope">
              <el-avatar :size="50" :src="'http://127.0.0.1:8000/' + scope.row.userImg"></el-avatar>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button type="text" @click="updateUser(scope.row.id)">编辑</el-button>
              <el-button type="text" @click="deleteUsers(scope.row.id)">移除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </template>

      <el-dialog title="修改用户" :visible.sync="dialogFormVisible">
        <el-form :model="userInfo">
          <el-form-item label="用户名称">
            <el-input v-model="userInfo.name" style="width: 200px"></el-input>
          </el-form-item>
          <el-form-item label="用户住址">
            <el-select v-model="userInfo.address" multiple filterable remote reserve-keyword placeholder="删除后修改" :remote-method="remoteMethod" :loading="loading">
              <el-option v-for="item in options" :key="item.id" :label="item.cityname" :value="item.cityname"> {{ item.cityname }}</el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="上传头像">
            <el-upload action="http://127.0.0.1:8000/admin/Upload/addFile" style="position: relative" ref="preUpload" list-type="picture-card" :auto-upload="true" :on-success="uploadSet">
              <i slot="default" class="el-icon-plus"></i>
              <div slot="file" slot-scope="{ file }">
                <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
                <span class="el-upload-list__item-actions">
                  <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                    <i class="el-icon-zoom-in"></i>
                  </span>
                </span>
              </div>
              <el-image style="width: 145px; height: 80%; position: absolute; top: 2px; left: 225px" :src="userInfo.userImg" fit="fill"></el-image>
            </el-upload>
          </el-form-item>
          <el-form-item label="用户密码">
            <el-input v-model="userInfo.password" style="width: 200px"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancelUpdate">取 消</el-button>
          <el-button type="primary" @click="sureUpdate">确 定</el-button>
        </div>
      </el-dialog>
      <footer>
        <el-pagination background layout="prev, pager, next" v-on:prev-click="prevPage" v-on:current-change="currentPage" v-on:next-click="nextPage" :total="pageSum * 10"> </el-pagination>
      </footer>
    </main>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import heads from "@/components/adminHead.vue";

import { selectPageUser, selectIdUser, selectAddress, updateUserInfo, deleteFile, deleteUser } from "@/api/getPostApi";

export default {
  //import引入的组件需要注入到对象中才能使用
  components: {
    heads,
  },
  data() {
    //这里存放数据
    return {
      loading: false,
      dialogFormVisible: false,
      tableData: [],
      page: 1,
      pageSum: 1,
      userInfo: {
        id: "",
        name: "",
        address: [],
        userImg: "",
        filePath: "",
        password: "",
      },
      options: [],
      formLabelWidth: "120px",
    };
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {
    remoteMethod(val) {
      this.loading = true;
      selectAddress(val).then((response) => {
        this.loading = false;
        this.options = response.data;
      });
    },
    uploadSet(val) {
      this.userInfo.filePath = val;
    },
    updateUser(id) {
      this.dialogFormVisible = true;
      selectIdUser(id).then((response) => {
        this.userInfo.id = response.data.id;
        this.userInfo.name = response.data.username;
        this.userInfo.address = [response.data.address];
        this.userInfo.userImg = `http://127.0.0.1:8000/${response.data.userImg}`;
        this.userInfo.password = response.data.password;
      });
    },
    sureUpdate() {
      this.dialogFormVisible = false;
      updateUserInfo(this.userInfo.id, this.userInfo.name, this.userInfo.address[0], this.userInfo.filePath, this.userInfo.password).then((response) => {
        if (response.data.status === 200) {
          this.$message({
            message: "恭喜你，成功修改",
            type: "success",
          });
        } else {
          this.$message.error("错了哦，修改失败");
        }
        this.tableData.forEach((vals, index) => {
          if (vals.id === this.userInfo.id) {
            this.tableData.splice(index, 1, { id: vals.id, username: this.userInfo.name, address: this.userInfo.address[0], userImg: this.userInfo.filePath ? this.userInfo.filePath : vals.userImg, addUserTime: vals.addUserTime });
          }
        });
        this.deleteImg();
      });
    },
    cancelUpdate() {
      this.dialogFormVisible = false;
      this.deleteImg();
      if (this.userInfo.filePath) {
        deleteFile(this.userInfo.filePath);
      }
    },
    deleteImg() {
      this.$refs.preUpload.uploadFiles.forEach((value, index) => {
        if (value.response === this.userInfo.filePath) {
          this.$refs.preUpload.uploadFiles.splice(index, 1);
        }
      });
      this.userInfo.filePath = "";
    },
    selectPageUser() {
      selectPageUser(this.page).then((response) => {
        console.log(response.data);
        this.pageSum = Math.ceil(response.data.userCount / 10);
        this.tableData = response.data.userList;
      });
    },
    prevPage() {
      this.page -= 1;
      this.selectPageUser();
    },
    nextPage() {
      this.page += 1;
      this.selectPageUser();
    },
    currentPage(value) {
      this.page = value;
      this.selectPageUser();
    },
    deleteUsers(id) {
      deleteUser(id).then((response) => {
        if (response.data.status === 200) {
          this.$message({
            message: "恭喜你，删除修改",
            type: "success",
          });
        } else {
          this.$message.error("错了哦，删除失败");
        }
        this.tableData = this.tableData.filter((val) => val.id !== id);
        if (!this.tableData.length) {
          this.prevPage();
        }
      });
    },
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {
    this.selectPageUser();
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>

<style lang="scss" scoped>
//@import url(); 引入公共css类
@import "@/style/mixin.scss";
footer {
  @include footer;
}
</style>
